/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;


import ClassesBasicas.Componente;
import ClassesBasicas.Selecao;
import Fachada.Fachada;
import erro.GeralException;
import erro.NegocioException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author ESDRAS
 */
public class CadastroSelecaoComponente extends javax.swing.JFrame {

    /**
     * Creates new form CadastroSelecao
     */
    Fachada fa;
    
    ArrayList<Componente> listaComponente = new ArrayList<Componente>();
    ArrayList<Selecao> listaSelecao = new ArrayList<Selecao>();
    
    /*nome da selecao selecionada na tabela*/
    public String nomeSelecao = new String(); 
    
    
    
    public CadastroSelecaoComponente() {
        
            initComponents();
            fa = new Fachada();
            preencherCampos();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setModalExclusionType(null);
        setResizable(false);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "Nome", "Atividade"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTable1);

        jButton1.setLabel("Atualizar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "Seleção Nome", "Pais"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTable2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Selecão"));

        jButton2.setLabel("Nova");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setLabel("Excluir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(25, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton3)
                .addContainerGap(26, Short.MAX_VALUE))
        );

        jButton2.getAccessibleContext().setAccessibleName("JButton2");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Componente"));

        jButton4.setLabel("Novo");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setLabel("Excluir");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE))
                .addGap(30, 30, 30))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton5)
                .addContainerGap(26, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 1, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(45, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(54, 54, 54))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /*Butao atualizar campos*/
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        atualizarCampos();
    
    }//GEN-LAST:event_jButton1ActionPerformed
    /**
     * Ao clicar na tabela a variavel global nomeSelecao instanciada novamente
     * lista todos os componentes pelo nomeSelecao
     */
    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
     try {
            nomeSelecao = jTable2.getValueAt(jTable2.getSelectedRow(),0).toString();
            
            listaComponente = (ArrayList<Componente>) fa.listarComponentePorCel(nomeSelecao);
           
        }  catch (NegocioException ex) {
            JOptionPane.showMessageDialog(null,ex.getMessage());
        }
        
        jTable1.setModel(geraModeloComponente(listaComponente));
        
    }//GEN-LAST:event_jTable2MouseClicked
    /**
     * 
     * Exibe o formulário cadastro componente
     */
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        
        new GUICadastroComponente().setVisible(true);
    }//GEN-LAST:event_jButton4ActionPerformed
    /*botao excluir componente*/
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
       
        
        int row = jTable1.getSelectedRow();
        
        if(row != -1){
            
            String nome = jTable1.getValueAt(row,0).toString().trim();
        
           int a =   JOptionPane.showConfirmDialog(rootPane, "Deseja mesmo excluir o Componente "+nome,"Excluir Componente",JOptionPane.YES_NO_OPTION);
           
           Componente comp = new Componente();
           comp.setNomeComponente(nome);
           
          if(a == 0){
                try {
                
                    fa.excluirComponnte(comp);
                
                } catch (NegocioException ex) {
                    JOptionPane.showMessageDialog(rootPane, ex.getMessage());
                } catch (GeralException ex) {
                    JOptionPane.showMessageDialog(rootPane, ex.getMessage());
                }
          }
           /*atualisa os compos logo apos excluir*/
          atualizarCampos();
        }
    }//GEN-LAST:event_jButton5ActionPerformed
    /*
     * Quando o formulario CadastroSelecaoComponente ganha 
     * foco executa o metodo atualizarcampos
     */
    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
       atualizarCampos();
    }//GEN-LAST:event_formWindowGainedFocus
    /*Exibe o formulário CadastroSelecao1*/
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        new CadastroSelecao1(this, rootPaneCheckingEnabled).setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed
    /*butao excluir uma selecao*/
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
     
        Selecao sel = new Selecao(); 
        
        sel.setNomeSelecao(nomeSelecao);
        
        int a =   JOptionPane.showConfirmDialog(rootPane, "Dejeja mesmo excluir a Selecao "+nomeSelecao,"Excluir Selecao",JOptionPane.YES_NO_OPTION);
        try {
        
        if(a == 0){ 
            fa.exvluirSelecao(sel);     
        }
        
        } catch (NegocioException ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage());
        } catch (GeralException ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage());
        }
        
        atualizarCampos();
    }//GEN-LAST:event_jButton3ActionPerformed
    /*
     * gera um modelo da tabela Componente e insere novas linhas
     * de acordo com o ArrayList passado por parametro
     */
   private DefaultTableModel geraModeloComponente(ArrayList<Componente> lista){
       
       /* Modelo com a sobrecarga do metodo iscelleditable retornando a false
        *  nao permitindo que o usuario edite a tabela.
        */
       DefaultTableModel modelo = new DefaultTableModel(){  
            public boolean isCellEditable(int rowIndex, int mColIndex) {  
                return false;  
            }  
        };
       
       modelo.addColumn("Nome");
       modelo.addColumn("Atividade");
       
       
       
       int i=0;
       ArrayList<String> valores = new ArrayList<String>();
       
       for(Componente comp : lista){
          
          valores.add(comp.getNomeComponente());
          valores.add(comp.getAtividade().getnome_Atividade());
          
          modelo.insertRow(i, valores.toArray());
        
          valores.clear();
          
          i++;
       }
        return modelo;
       
   }
   /*
     * gera um modelo da tabela Selecao e insere novas linhas
     * de acordo com o ArrayList passado por parametro
     */
   private DefaultTableModel geraModeloSelecao(ArrayList<Selecao> lista){
       
       
        /* Modelo com a sobrecarga do metodo iscelleditable retornando a false
        *  nao permitindo que o usuario edite a tabela.
        */
       DefaultTableModel modelo = new DefaultTableModel(){  
            public boolean isCellEditable(int rowIndex, int mColIndex) {  
                return false;  
            }  
        };
       
       modelo.addColumn("Nome Selecao");
       modelo.addColumn("Pais");
       
       
       int i=0;
       ArrayList<String> valores = new ArrayList<String>();
       
       for(Selecao sel : lista){
          
          valores.add(sel.getNomeSelecao());
          valores.add(sel.getPais().getNomePais());
          
          modelo.insertRow(i, valores.toArray());
         
          valores.clear();
          
          i++;
       }
        return modelo;
       
   }
   /*prenche o formulario ao iniciar-lo*/
   private void preencherCampos(){
        
      
       try{
            
            listaSelecao = fa.listarSelecao();
            
        } catch (NegocioException ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage());
        
        }
        jTable2.setModel(geraModeloSelecao(listaSelecao));
        
     }
   
   public void atualizarCampos(){
            
            try {
                if(!nomeSelecao.equals(""))
                    listaComponente = (ArrayList<Componente>) fa.listarComponentePorCel(nomeSelecao);
                listaSelecao = fa.listarSelecao();
            }catch (NegocioException ex) {
                JOptionPane.showMessageDialog(rootPane, ex.getMessage());
            }
                jTable1.setModel(geraModeloComponente(listaComponente));
                jTable2.setModel(geraModeloSelecao(listaSelecao));
            
   }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastroSelecaoComponente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastroSelecaoComponente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastroSelecaoComponente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastroSelecaoComponente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new CadastroSelecaoComponente().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration//GEN-END:variables
}
